package cn.com.client.send;

import cn.com.common.Constant;
import cn.com.common.model.ProbeModel;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 探测key累加器
 *
 * @author jiaming
 */
public class RecordAccumulator {

    protected static final LinkedBlockingQueue<ProbeModel> QUEUE = new LinkedBlockingQueue<>(Constant.QUEUE_SIZE);

    public void append(String key) {
        if (StringUtils.isBlank(key)) {
            throw new IllegalArgumentException("param key is null");
        }
        ProbeModel probeModel = new ProbeModel();
        probeModel.setKeyType(0);
        probeModel.setAppName(Constant.APP_NAME);
        probeModel.setKey(key);
        try {
            QUEUE.offer(probeModel, Constant.QUEUE_OFFER_WAIT, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public ProbeModel record() {
        try {
            return QUEUE.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<ProbeModel> record(List<ProbeModel> results, int maxResultSize) {
        if (results == null) {
            throw new IllegalArgumentException("param 'results' is null");
        }
        if (maxResultSize <= 0) {
            throw new IllegalArgumentException("param maxResultSize must > 0");
        }
        QUEUE.drainTo(results, maxResultSize);
        return results;
    }

}